package org.petstore.web.servlet;

import org.petstore.domain.Account;
import org.petstore.persistence.ShoppingCartDAO;
import org.petstore.persistence.impl.ShoppingCartDAOImpl;
import org.petstore.service.impl.OrderServiceImpl;
import org.petstore.util.Cart;
import org.petstore.domain.Order;
import org.petstore.persistence.ItemDAO;
import org.petstore.persistence.impl.ItemDAOImpl;
import org.petstore.service.OrderService;
import org.petstore.web.servlet.util.MyUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * @projectName: MyWebProject
 * @package: org.petstore.web.servlet
 * @className: ConfirmOrderServlet
 * @author: Eric
 * @description: TODO
 * @date: 2021/10/31 16:03
 * @version: 1.0
 */
public class ConfirmOrderServlet extends HttpServlet {

    OrderService orderService = MyUtil.getApplicationContext().getBean("orderService", OrderService.class);
    ShoppingCartDAO shoppingCartDAO = MyUtil.getApplicationContext().getBean("shoppingCartDao", ShoppingCartDAO.class);

    private Order order;
    private Account account;
    private static final String VIEW_ORDER = "/WEB-INF/jsp/order/ViewOrder.jsp";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        order = (Order) session.getAttribute("order");
        order.setStatus("OK");
        order.setOrderDate(new Date());//java.util.Date 无参数默认系统当前时间
        account = new Account();
        account = (Account) session.getAttribute("loginUser");
        Cart cart = (Cart) session.getAttribute("cart");
        order.setTotalPrice(cart.getSubTotal());

        orderService.insertOrder(order);
        session.setAttribute("order", order);
        request.getRequestDispatcher(VIEW_ORDER).forward(request, response);
        cart = null;
        session.setAttribute("cart", cart);

        shoppingCartDAO.deleteCart(account.getUsername());
    }
}
